package com.aviator.executor;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.FunctionLoader;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorBoolean;
import com.googlecode.aviator.runtime.type.AviatorFunction;
import com.googlecode.aviator.runtime.type.AviatorObject;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @Author: Jiangxx
 * @Date: 2021/12/30
 * @Description: 函数加载器
 */
public class AviatorExecutor06 {

    public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException {
        AviatorEvaluator.addStaticFunctions("str", StringUtils.class);
        /* 导入自定义加载器 */
        AviatorEvaluator.addFunctionLoader(new FunctionLoaderTest());

        /* org.springframework.util.StringUtils包下没有isBlank()方法，将调用已加载的自定义的函数方法 */
        System.out.println(AviatorEvaluator.execute("str.isBlank('')"));
    }
}

/**
 * 自定义函数加载器
 */
class FunctionLoaderTest implements FunctionLoader {

    @Override
    public AviatorFunction onFunctionNotFound(String s) {
        return new IsBlankFunction();
    }
}

/**
 * 自定义isBlank函数方法
 */
class IsBlankFunction extends AbstractFunction {

    @Override
    public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {
        if (arg1 != null) {
            if (arg1.getValue(env).equals("")) {
                return AviatorBoolean.valueOf(true);
            }
        }
        return AviatorBoolean.valueOf(false);
    }

    @Override
    public String getName() {
        return "isBlank";
    }
}
